import React, { useState, useEffect, useRef } from 'react'
import { Button, Space, Table, TableProps, Drawer } from 'antd'
import style from './RoleList.module.scss'
import { List } from '../../service/index-roleList'
import CreatePart from './create/Create'
import Delete from './delete/Delete'
import PermissionTree from './permissionTree/PermissionTree'

// 列表数据类型
interface DataType {
  key: string;
  name: string;
  value: string;
  creator: string;
  createTime: string;
  permission: string[];
}


// const { Option } = Select;

// ------------------------------------------------------------------------------------------
const RoleList: React.FC = () => {
  const [list, setList] = useState<DataType[]>([]); // 列表数据
  const characterPermission = useRef<string[]>([]); // 角色拥有的权限列表
  const characterId = useRef<string>(''); // 角色id

  // 表格列
  const columns: TableProps['columns'] = [
    {
      title: '角色',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色关键字',
      dataIndex: 'value',
      key: 'value',
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <button className={style.changeBtn} onClick={() => {
            showDrawer();
            characterPermission.current = record.permission
            characterId.current = record._id
          }}>分配角色</button>
          <Delete id={record._id} getData={getData} />
        </Space>
      ),
    },
  ];
  
  // 修改日期格式的函数
  const toLocaleDateString = (date: string) => {
    const dateObj = new Date(date)
    return dateObj.toLocaleString()
  }

  // 获取角色列表数据
  const getData = () => {
    List()
      .then(res => {
        const arr = res.data.data.list
        arr.forEach((item: DataType) => {
          item.createTime = toLocaleDateString(item.createTime)
        })
        setList(arr)
      })
      .catch(err => console.log(err))
  }

  useEffect(() => {
    // 获取角色列表
    getData()

  }, []);

  const [open, setOpen] = useState(false); // 弹窗状态

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };


  return <div>
    <CreatePart setGetData={getData} />
    <Table<DataType> columns={columns} dataSource={list} rowKey={'name'} />
    <Drawer title="分配角色" onClose={onClose} open={open} className={style.drawer}>
      <PermissionTree characterPermission={characterPermission.current} onClose={onClose} characterId={characterId.current} />
    </Drawer>
  </div>
};

export default RoleList;